package com.ruicar.afs.cloud.seats.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.seats.condition.DailyScheduleCondition;
import com.ruicar.afs.cloud.seats.entity.BaseHoliday;
import com.ruicar.afs.cloud.seats.entity.OpraHoliday;
import com.ruicar.afs.cloud.seats.service.BaseHolidayService;
import com.ruicar.afs.cloud.seats.service.OpraHolidayService;
import com.ruicar.afs.cloud.seats.util.DateUtil;
import com.ruicar.afs.cloud.seats.util.WorkFlag;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author tiankai
 * @Describe 工作日历日程安排
 * Created on 2020-05-15
 */
@Slf4j
@RestController
@RequestMapping("/group")
@AllArgsConstructor
@Api(description = "工作日历接口")
public class DailyScheduleController {

    @Autowired
    private BaseHolidayService service;
    @Autowired
    private OpraHolidayService holidayService;

    @GetMapping(value = {"/getScheduleInfo"})
    @ApiOperation(value = "获取日程信息")
    public IResponse<List<DailyScheduleCondition>> getScheduleInfo() {
        List<DailyScheduleCondition> conditionList = new ArrayList();
        List<BaseHoliday> list = service.list();
        if (list != null && !list.isEmpty()) {
            for (BaseHoliday baseHoliday : list) {
                OpraHoliday opraHoliday = holidayService.getOne(Wrappers.<OpraHoliday>query().lambda().eq(OpraHoliday::getLoginName, SecurityUtils.getUsername()).eq(OpraHoliday::getYear, baseHoliday.getYear()).eq(OpraHoliday::getMonth, baseHoliday.getMonth()).eq(OpraHoliday::getDay, baseHoliday.getDay()));
                if(ObjectUtil.isNotNull(opraHoliday)){
                    BeanUtil.copyProperties(opraHoliday,baseHoliday);
                    getDailyInfo(conditionList,baseHoliday);
                }else{
                    getDailyInfo(conditionList,baseHoliday);
                }
            }
        }
        return IResponse.success(conditionList);
    }

    public void getDailyInfo(List<DailyScheduleCondition> conditionList,BaseHoliday baseHoliday){
        String date = baseHoliday.getYear() + baseHoliday.getMonth() + baseHoliday.getDay();
        DailyScheduleCondition condition = new DailyScheduleCondition();
        condition.setStart(date);
        condition.setTitle(baseHoliday.getTimeAm() + baseHoliday.getWorkFlagAm());
        DailyScheduleCondition condition1 = new DailyScheduleCondition();
        condition1.setStart(date);
        condition1.setTitle(baseHoliday.getTimePm() + baseHoliday.getWorkFlagPm());
        if(WorkFlag.WORK_FLAG.getCode().equals(baseHoliday.getWorkFlagAm())){
            condition.setColor(WorkFlag.WORK_COLOR.getCode());
            condition1.setColor(WorkFlag.WORK_COLOR.getCode());
        }else{
            condition.setColor(WorkFlag.REST_COLOR.getCode());
            condition1.setColor(WorkFlag.REST_COLOR.getCode());
        }
        conditionList.add(condition);
        conditionList.add(condition1);
        if(StringUtil.isNotEmpty(baseHoliday.getRemarks())){
            DailyScheduleCondition condition2 = new DailyScheduleCondition();
            condition2.setStart(date);
            condition2.setTitle("备注:"+baseHoliday.getRemarks());
            condition2.setColor(WorkFlag.GREY_COLOR.getCode());
            conditionList.add(condition2);
        }
    }

    @SneakyThrows
    @RequestMapping(value = "/batchUpdateCalendar", method = RequestMethod.POST)
    @ApiOperation(value = "批量设定日历")
    public IResponse<DailyScheduleCondition> batchUpdateCalendar(@RequestBody DailyScheduleCondition condition) {
        String[] strArr = condition.getSetDate().split("\\,");
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for(int i = 0; i < strArr.length; ++i){
            Calendar c = Calendar.getInstance();
            c.setTime(dateFormat.parse(strArr[i]));
            c.add(Calendar.DATE, 1);
            List<String> roles = SecurityUtils.getRoles();
            if(condition.getWeek()!=null&&!condition.getWeek().isEmpty()){
                String strWeek = DateUtil.getCurrentWeekOfMonth(c);
                if(condition.getWeek().contains(strWeek)){
                    if(roles.contains("ROLE_APPROVER_ADMIN")){
                        updateBaseHoliday(condition,dateFormat.parse(strArr[i]),strWeek);
                    }else{
                        updateOpraHoliday(condition,dateFormat.parse(strArr[i]),strWeek,"");
                    }
                }
            }else{
                if(roles.contains("ROLE_APPROVER_ADMIN")){
                    updateBaseHoliday(condition,dateFormat.parse(strArr[i]),"");
                }else{
                    updateOpraHoliday(condition,dateFormat.parse(strArr[i]),"","");
                }
            }
        }
        return new IResponse().setData(true);
    }

    private void updateBaseHoliday(DailyScheduleCondition condition, Date date, String s) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String title = dateFormat.format(date);
        String year = title.substring(0, 4);
        String month = title.substring(5, 7);
        String day = title.substring(8, 10);
        BaseHoliday baseHoliday = service.getOne(Wrappers.<BaseHoliday>query().lambda().eq(BaseHoliday::getYear, year).eq(BaseHoliday::getMonth, month).eq(BaseHoliday::getDay, day));
        if(ObjectUtil.isNull(baseHoliday)){
            baseHoliday = new BaseHoliday();
            baseHoliday.setWeek(s);
            baseHoliday.setYear(year);
            baseHoliday.setMonth(month);
            baseHoliday.setDay(day);
            updateSchedule(condition,baseHoliday);
        }else{
            updateSchedule(condition,baseHoliday);
        }
        List<OpraHoliday> list = holidayService.list(Wrappers.<OpraHoliday>query().lambda().eq(OpraHoliday::getYear, year).eq(OpraHoliday::getMonth, month).eq(OpraHoliday::getDay, day));
        if(list!=null && !list.isEmpty()){
            for(OpraHoliday  opraHoliday : list){
                updateOpraHoliday(condition,opraHoliday);
            }
        }
    }

    private void updateOpraHoliday(DailyScheduleCondition condition, Date date, String s,String loginName) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String title = dateFormat.format(date);
        String year = title.substring(0, 4);
        String month = title.substring(5, 7);
        String day = title.substring(8, 10);
        if(StringUtil.isEmpty(loginName)){
            loginName = SecurityUtils.getUsername();
        }
        OpraHoliday opraHoliday = holidayService.getOne(Wrappers.<OpraHoliday>query().lambda().eq(OpraHoliday::getLoginName, loginName).eq(OpraHoliday::getYear, year).eq(OpraHoliday::getMonth, month).eq(OpraHoliday::getDay, day));
        if(ObjectUtil.isNull(opraHoliday)){
            opraHoliday = new OpraHoliday();
            opraHoliday.setLoginName(loginName);
            opraHoliday.setWeek(s);
            opraHoliday.setYear(year);
            opraHoliday.setMonth(month);
            opraHoliday.setDay(day);
            updateOpraHoliday(condition,opraHoliday);
        }else{
            updateOpraHoliday(condition,opraHoliday);
        }
    }

    /**
     * @Describe 个人日程更新
     * Created on 2020-05-15
     * @author tiankai
     */
    public void updateOpraHoliday(DailyScheduleCondition condition, OpraHoliday opraHoliday) {
        if(WorkFlag.WORK_FLAG.getCode().equals(condition.getWorkStatus())){
            List amTime = condition.getAmTime();
            List pmTime = condition.getPmTime();
            String timeAm = "";
            for (int i = 0; i < amTime.size(); i++) {
                timeAm = timeAm + (String) amTime.get(i) + "-";
            }
            String timePm = "";
            for (int i = 0; i < pmTime.size(); i++) {
                timePm = timePm + (String) pmTime.get(i) + "-";
            }
            opraHoliday.setTimeAm(timeAm.substring(0, timeAm.length() - 1));
            opraHoliday.setTimePm(timePm.substring(0, timePm.length() - 1));
        }else {
            opraHoliday.setTimeAm(WorkFlag.TIME_AM.getCode());
            opraHoliday.setTimePm(WorkFlag.TIME_PM.getCode());
        }
        opraHoliday.setWorkFlagAm(condition.getWorkStatus());
        opraHoliday.setWorkFlagPm(condition.getWorkStatus());
        opraHoliday.setRemarks(condition.getRemarks());
        holidayService.saveOrUpdate(opraHoliday);
    }

    @SneakyThrows
    @RequestMapping(value = "/updateDay", method = RequestMethod.POST)
    @ApiOperation(value = "更新当天日程")
    public IResponse<DailyScheduleCondition> updateDay(@RequestBody DailyScheduleCondition condition) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String year = condition.getDate().substring(0, 4);
        String month = condition.getDate().substring(5, 7);
        String day = condition.getDate().substring(8, 10);
        List<String> roles = SecurityUtils.getRoles();
        if(roles.contains("ROLE_APPROVER_ADMIN")){
            updateBaseHoliday(condition,formatter.parse(condition.getDate()),"");
        }else{
            if(StringUtil.isEmpty(condition.getLoginName())){
                condition.setLoginName(SecurityUtils.getUsername());
            }
            OpraHoliday opraHoliday = holidayService.getOne(Wrappers.<OpraHoliday>query().lambda().eq(OpraHoliday::getLoginName,condition.getLoginName()).eq(OpraHoliday::getYear, year).eq(OpraHoliday::getMonth, month).eq(OpraHoliday::getDay, day));
            if (ObjectUtil.isNotNull(opraHoliday)) {
                updateOpraHoliday(condition,opraHoliday);
            }else{
                Calendar c = Calendar.getInstance();
                c.setTime(formatter.parse(condition.getDate()));
                c.add(Calendar.DATE, 1);
                opraHoliday = new OpraHoliday();
                opraHoliday.setLoginName(SecurityUtils.getUsername());
                opraHoliday.setWeek(DateUtil.getCurrentWeekOfMonth(c));
                opraHoliday.setYear(year);
                opraHoliday.setMonth(month);
                opraHoliday.setDay(day);
                updateOpraHoliday(condition,opraHoliday);
            }
        }
        return new IResponse().setData(true);
    }

    /**
     * @Describe 系统日程更新
     * Created on 2020-05-15
     * @author tiankai
     */
    public void updateSchedule(DailyScheduleCondition condition, BaseHoliday baseHoliday) {
        if(WorkFlag.WORK_FLAG.getCode().equals(condition.getWorkStatus())){
            List amTime = condition.getAmTime();
            List pmTime = condition.getPmTime();
            String timeAm = "";
            for (int i = 0; i < amTime.size(); i++) {
                if (!"".equals((String) amTime.get(i))) {
                    timeAm = timeAm + (String) amTime.get(i) + "-";
                }
            }
            String timePm = "";
            for (int i = 0; i < pmTime.size(); i++) {
                if (!"".equals((String) pmTime.get(i))) {
                    timePm = timePm + (String) pmTime.get(i) + "-";
                }
            }
            baseHoliday.setTimeAm(timeAm.substring(0, timeAm.length() - 1));
            baseHoliday.setTimePm(timePm.substring(0, timePm.length() - 1));
        }else{
            baseHoliday.setTimeAm(WorkFlag.TIME_AM.getCode());
            baseHoliday.setTimePm(WorkFlag.TIME_PM.getCode());
        }
        baseHoliday.setWorkFlagAm(condition.getWorkStatus());
        baseHoliday.setWorkFlagPm(condition.getWorkStatus());
        baseHoliday.setRemarks(condition.getRemarks());
        service.saveOrUpdate(baseHoliday);
    }

    @RequestMapping(value = "/queryOpraHolidayInfo", method = RequestMethod.POST)
    @ApiOperation(value = "查看个人日程信息")
    public IResponse<OpraHoliday> queryOpraHolidayInfo(@RequestBody DailyScheduleCondition condition) {
        String year = condition.getDate().substring(0, 4);
        String month = condition.getDate().substring(5, 7);
        String day = condition.getDate().substring(8, 10);
        OpraHoliday opraHoliday = holidayService.getOne(Wrappers.<OpraHoliday>query().lambda().eq(OpraHoliday::getLoginName, SecurityUtils.getUsername()).eq(OpraHoliday::getYear, year).eq(OpraHoliday::getMonth, month).eq(OpraHoliday::getDay, day));
        if(ObjectUtil.isNotNull(opraHoliday)){
            return IResponse.success(opraHoliday);
        }else{
            BaseHoliday baseHoliday = service.getOne(Wrappers.<BaseHoliday>query().lambda().eq(BaseHoliday::getYear, year).eq(BaseHoliday::getMonth, month).eq(BaseHoliday::getDay, day));
            if(ObjectUtil.isNotNull(baseHoliday)){
                OpraHoliday holiday = new OpraHoliday();
                BeanUtil.copyProperties(baseHoliday,holiday);
                return IResponse.success(holiday);
            }
            return IResponse.success(null);
        }
    }

    @SneakyThrows
    @RequestMapping(value = "/personalCalendarUpdate", method = RequestMethod.POST)
    @ApiOperation(value = "坐席个人日历设定")
    public IResponse<DailyScheduleCondition> personalCalendarUpdate(@RequestBody DailyScheduleCondition condition) {
        String[] strArr = condition.getSetDate().split("\\,");
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for(int i = 0; i < strArr.length; ++i){
            Calendar c = Calendar.getInstance();
            c.setTime(dateFormat.parse(strArr[i]));
            c.add(Calendar.DATE, 1);
            String[] loginNameArr = condition.getLoginName().split("\\,");
            if(condition.getWeek()!=null&&!condition.getWeek().isEmpty()){
                String strWeek = DateUtil.getCurrentWeekOfMonth(c);
                if(condition.getWeek().contains(strWeek)){
                    for(int j = 0; j < loginNameArr.length; ++j){
                        updateOpraHoliday(condition,dateFormat.parse(strArr[i]),strWeek,loginNameArr[j]);
                    }
                }
            }else{
                for(int j = 0; j < loginNameArr.length; ++j){
                    updateOpraHoliday(condition,dateFormat.parse(strArr[i]),"",loginNameArr[j]);
                }
            }
        }
        return new IResponse().setData(true);
    }

    @GetMapping(value = {"/queryCalenderRecord"})
    @ApiOperation(value = "获取日历记录信息")
    public IResponse<IPage<BaseHoliday>> queryCalenderRecord(@ModelAttribute DailyScheduleCondition condition) {
        IPage<List<BaseHoliday>> listIPage = service.page(new Page(condition.getPageNumber(), condition.getPageSize()));
        List<BaseHoliday> list = (List)listIPage.getRecords();
        for(BaseHoliday baseHoliday : list){
            OpraHoliday opraHoliday = holidayService.getOne(Wrappers.<OpraHoliday>query().lambda().eq(OpraHoliday::getLoginName, condition.getLoginName()).eq(OpraHoliday::getYear, baseHoliday.getYear()).eq(OpraHoliday::getMonth, baseHoliday.getMonth()).eq(OpraHoliday::getDay, baseHoliday.getDay()));
            if(ObjectUtil.isNotNull(opraHoliday)){
                BeanUtil.copyProperties(opraHoliday,baseHoliday);
            }
            baseHoliday.setCreateTime(baseHoliday.getCreateTime());
            baseHoliday.setDate(baseHoliday.getYear()+"-"+baseHoliday.getMonth()+"-"+baseHoliday.getDay());
        }
        return IResponse.success(listIPage);
    }

    @SneakyThrows
    @RequestMapping(value = "/updateSeatsDay", method = RequestMethod.POST)
    @ApiOperation(value = "坐席中更新当天日程")
    public IResponse<DailyScheduleCondition> updateSeatsDay(@RequestBody DailyScheduleCondition condition) {
        String year = condition.getDate().substring(0, 4);
        String month = condition.getDate().substring(5, 7);
        String day = condition.getDate().substring(8, 10);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        if(StringUtil.isEmpty(condition.getLoginName())){
            condition.setLoginName(SecurityUtils.getUsername());
        }
        OpraHoliday opraHoliday = holidayService.getOne(Wrappers.<OpraHoliday>query().lambda().eq(OpraHoliday::getLoginName,condition.getLoginName()).eq(OpraHoliday::getYear, year).eq(OpraHoliday::getMonth, month).eq(OpraHoliday::getDay, day));
        if (ObjectUtil.isNotNull(opraHoliday)) {
            updateOpraHoliday(condition,opraHoliday);
        }else{
            c.setTime(formatter.parse(condition.getDate()));
            c.add(Calendar.DATE, 1);
            opraHoliday = new OpraHoliday();
            opraHoliday.setLoginName(condition.getLoginName());
            opraHoliday.setWeek(DateUtil.getCurrentWeekOfMonth(c));
            opraHoliday.setYear(year);
            opraHoliday.setMonth(month);
            opraHoliday.setDay(day);
            updateOpraHoliday(condition,opraHoliday);
        }
        return new IResponse().setData(true);
    }
}


